<template>
  <div>
    <div class="page_top">
      <div class="left_btn" @click="back">
        <img src="../../assets/image/back.png" alt=""/>
      </div>
      <crumbs basetitle="财务" :title="title" :title1="title1"></crumbs>
    </div>
    <div class="tab">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="月初预付" name="first">
          <el-card>
            <div class="date">
              <div class="choosedate">
                <span class="demonstration">月份：</span>
                <el-date-picker :clearable="false" v-model="monthstart" type="month" placeholder="选择时间"
                                @change="changedateokstart"/>
              </div>
              <el-button @click="reset('start')">重置</el-button>
            </div>
          </el-card>
          <!-- 月初预付空状态 -->
          <el-empty v-show="monthstartdata.length === 0"
                    crossorigin="anonymous"
                    image="https://pc-custom-admin.oss-cn-shanghai.aliyuncs.com/img/noData.png"/>
          <el-card class="table-list" v-for="(ele, index) in monthstartdata" :key="index">
            <div class="tables">
              <div class="l">
                <div class="top">
                  <img crossorigin="anonymous" :src="ele.insurCompanyLogo" alt=""/>
                  <span class="big">{{ ele.insurCompanyName }}</span>
                </div>
                <div>
                  <span class="small">1号在保人数：</span><span class="bord">{{ ele.insurNumber }}人</span>
                </div>
                <div>
                  <span class="small">预付金额：</span><span class="bord">¥{{ ele.prepayCost }}</span>
                </div>
                <div class="dc_btn" @click="upfilestart(ele.insurCompany)">
                  <img src="../../assets/image/导出@2x.png" alt=""/>
                  <span>导出</span>
                </div>
              </div>
              <div class="r">
                <el-table :data="ele.demodata" style="width: 100%">
                  <el-table-column prop="date" width="150" align="center" label="方案" fixed>
                  </el-table-column>
                  <template v-for='(col, i) in ele.dateList' :key="col.label">
                    <el-table-column :show-overflow-tooltip="true" :label="col.label" width="100"
                                     align="center">
                      <template v-for="(item, index) in col.list" :key="index">
                        <el-table-column :label="item.label" min-width="150">
                          <template #default="scope">
                            <span>
                              {{ scope.row.list[item.prop] }}
                            </span>
                          </template>
                        </el-table-column>
                      </template>
                    </el-table-column>
                  </template>
                </el-table>
              </div>
            </div>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="月底结算" name="second">
          <el-card>
            <div class="date">
              <div class="choosedate">
                <span class="demonstration">月份：</span>
                <el-date-picker :clearable="false" v-model="monthend" type="month" placeholder="选择时间"
                                @change="changedateokend"/>
              </div>
              <el-button @click="reset('end')">重置</el-button>
            </div>
          </el-card>
          <el-card style="margin-top: 20px">
            <div class="t">
              <div @click="changet_itemindex(index)" :class="{ t_item: true, active: t_itemindex === index }"
                   v-for="(ele, index) in monthenddata" :key="index">
                <div class="t_l">
                  <div class="t_lone">
                    <img crossorigin="anonymous" :src="ele.insurCompanyLogo" alt=""/><span>{{
                      ele.insurCompanyName
                    }}</span>
                  </div>
                  <div>
                    <span class="amsll">总人数：</span><span class="bord">{{ ele.headcount }}人</span>
                  </div>
                  <div>
                    <span class="amsll">总金额：</span><span class="bord">¥{{ ele.price }}</span>
                  </div>
                  <div>
                    <span class="amsll">总成本金额：</span><span class="bord">¥{{ ele.cost }}</span>
                  </div>
                </div>
                <div class="t_r" @click.stop="upfileend(ele.insurCompany)">
                  <img src="../../assets/image/导出@2x.png" alt=""/><span>导出</span>
                </div>
              </div>
            </div>
            <div class="b">
              <el-empty v-show="mounthendshow === 0"
              crossorigin="anonymous"
                        image="https://pc-custom-admin.oss-cn-shanghai.aliyuncs.com/img/noData.png"/>
              <table class="list-table" v-show="mounthendshow === 1">
                <thead>
                <tr class="table-title aaa">
                  <th class="tac" style="border-right: 1px solid #cccccc" :colspan="alarms_models.length / 3 + 1">
                    加保
                  </th>
                  <th class="tac" style="border-right: 1px solid #cccccc" :colspan="alarms_models.length / 3">
                    减保
                  </th>
                  <th class="tac" :colspan="alarms_models.length / 3">
                    汇总
                  </th>
                  <th class="tac" :colspan="1" style="background-color: #f4f4f7">
                    总计
                  </th>
                </tr>
                <tr class="table-title bbb">
                  <th class="tac" style="
                        background-color: #eaeaef;
                        position: sticky;
                        left: 0;
                        z-index: 3;
                        box-shadow: 5px 0 0px #1a191a;
                      ">
                    方案
                  </th>
                  <th class="tac" v-for="(item, i) in alarms_models" :key="i">
                    {{ item }}
                  </th>
                  <th class="tac" style="
                        background-color: #eaeaef;
                        position: sticky;
                        left: 0;
                        z-index: 3;
                        box-shadow: 5px 0 0px #1a191a;
                      "></th>
                </tr>
                </thead>
                <tbody>
                <tr class="table-content" v-for="(item, i) in alarms_ir">
                  <td class="tac1" v-for="(ele, index) in item" :key="i">
                    {{ ele }}
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, computed, onActivated} from 'vue'
import {ElMessage} from 'element-plus'
import {useRouter} from 'vue-router'
import dayjs from 'dayjs'
import {
  getmonthstartapi,
  getmonthendapi,
  getmonthendexcelapi,
  getmonthstartexcelapi,
} from '../../api/api'
import baseurl from '../../api/env'
import crumbs from '../../components/crumbs.vue'

const router = useRouter()
onActivated(() => {
  const m =
      new Date().getMonth() + 1 >= 10
          ? new Date().getMonth() + 1
          : `0${new Date().getMonth() + 1}`
  const y = new Date().getFullYear()
  monthstart.value = y + '-' + m
  getmonthstart()
})
const alarms_ir = ref<any>([])
const alarms_models = ref<any>([])

const getmonthstart = () => {
  getmonthstartapi(monthstart.value).then((res: any) => {
    res.forEach((ele: any, i: any) => {
      ele.dateList = [] as any
      ele.demodata = [{
        date: '人数',
        list: {}
      },
        {
          date: '金额',
          list: {}
        },
        {
          date: '成本保费',
          list: {}
        }]
      ele.companyPlans.forEach((j: any, k: any) => {
        const temp = {
          label: j.insurCompanyPlanName,
          list: [] as any
        }
        console.log(4554, j.insurCompanyPlanName, j.headCounts)
        j.level.forEach((x: any, y: any) => {
          // console.log(111, j.headCounts, x, y)
          ele.demodata[0].list[j.insurCompanyPlanName + x] = j.headCounts[y]
          ele.demodata[1].list[j.insurCompanyPlanName + x] = j.totalPrices[y]
          ele.demodata[2].list[j.insurCompanyPlanName + x] = j.totalCosts[y]
          temp.list.push({
            label: x + '类',
            prop: j.insurCompanyPlanName + x
          })
        })
        console.log(66666, j.insurCompanyPlanName, ele.demodata[0])
        ele.dateList.push(temp)
      })
    })
    monthstartdata.value = res
    monthenddata.value = res
    console.log(res, 11111)
  })
}
const getmonthend = () => {
  getmonthendapi(monthend.value).then((res) => {
    // console.log(res);
    monthenddata.value = res
    if (monthenddata.value[0].planDetailData.length === 0) {
      console.log('暂无')
      mounthendshow.value = 0
    } else {
      mounthendshow.value = 1
      console.log(monthenddata.value[0].planDetailData)
      const arr: any = []
      monthenddata.value[0].planDetailData[0].planSummarizing.forEach(
          (ele: any, index: number) => {
            arr.push(ele.insurCompanyPlanName)
          }
      )
      alarms_models.value = [...arr, ...arr, ...arr]
      // 定义一个数组result来存储最终结果
      const result = []
      // 遍历data数组
      for (const item of monthenddata.value[0].planDetailData) {
        const {day, planSummarizing} = item
        const summary = [day]
        // 遍历planSummarizing数组，将每个对象中的四个值依次加入summary数组中
        for (const p of planSummarizing) {
          const {plusInsurMoney, minusInsurMoney, summarizingMoney} = p
          summary.push(plusInsurMoney)
        }
        for (const p of planSummarizing) {
          const {plusInsurMoney, minusInsurMoney, summarizingMoney} = p
          summary.push(minusInsurMoney)
        }
        for (const p of planSummarizing) {
          const {plusInsurMoney, minusInsurMoney, summarizingMoney} = p
          summary.push(summarizingMoney)
        }
        // 将每个日期对应的数据放入result数组中
        result.push(summary)
      }
      result.forEach((ele: any, index: number) => {
        var num = (ele.length - 1) / 3
        var total = 0
        for (let index = num * 2 + 1; index < num * 2 + 1 + num; index++) {
          total += ele[index]
        }
        ele[ele.length] = total.toFixed(3)
      })
      console.log(result)
      alarms_ir.value = result
    }
  })
}
const monthstart = ref('')
const monthend = ref('')
const monthstartdata = ref<any>([])
const monthenddata = ref<any>([])

const title = ref<string>('保司对账')
const title1 = ref<string>('月初预付')
const activeName = ref('first')
// 切换tab事件
const handleClick = (tab: any, event: Event) => {
  const m =
      new Date().getMonth() + 1 >= 10
          ? new Date().getMonth() + 1
          : `0${new Date().getMonth() + 1}`
  const y = new Date().getFullYear()
  monthend.value = y + '-' + m
  // monthend.value = "2022-12";
  console.log(tab.props.label)
  if (tab.props.label === '月底结算') {
    getmonthend()
  } else {
    getmonthstart()
  }
  title1.value = tab.props.label
}

const initDate = () => {
  const year = dayjs().year()
  const month = dayjs().month() + 1 > 9 ? dayjs().month() + 1 : `0${dayjs().month() + 1}`
  return year + '-' + month
}

// 选定日期触发事件
const changedateokstart = (val: any) => {
  const year = val.getFullYear()
  const mounth =
      val.getMonth() + 1 >= 10 ? val.getMonth() + 1 : `0${val.getMonth() + 1}`
  monthstart.value = year + '-' + mounth
  // console.log(monthstart.value);
  getmonthstart()
}
const changedateokend = (val: any) => {
  t_itemindex.value = 0
  const year = val.getFullYear()
  const mounth =
      val.getMonth() + 1 >= 10 ? val.getMonth() + 1 : `0${val.getMonth() + 1}`
  monthend.value = year + '-' + mounth
  // console.log(monthend.value);
  getmonthend()
}

// 重置按钮
const reset = (type: string) => {
  if (type === 'start') {
    monthstart.value = initDate()
    getmonthstart()
  } else if (type === 'end') {
    monthend.value = initDate()
    getmonthend()
  }
}
// 导出月初按钮
const upfilestart = (val: any) => {
  console.log(monthstart.value)
  getmonthstartexcelapi({
    exportMonth: monthstart.value,
    insurCompany: val,
  }).then((res) => {
    ElMessage({
      message: '导出成功',
      type: 'success',
    })
    window.location.href =
        baseurl + '/common/download?delete=true&fileName=' + res
  })
}
// 导出月初按钮
const upfileend = (val: any) => {
  getmonthendexcelapi({
    exportMonth: monthend.value,
    insurCompany: val,
  }).then((res) => {
    ElMessage({
      message: '导出成功',
      type: 'success',
    })
    window.location.href =
        baseurl + '/common/download?delete=true&fileName=' + res
  })
}
// 返回
const back = () => {
  router.back()
}
const rowClass = ({row, column, rowIndex, columnIndex}: any) => {
  if (rowIndex === 1) {
    return {
      display: 'none',
    }
  }
}
const mounthendshow = ref(1)
const t_itemindex = ref(0)
const changet_itemindex = (i: number) => {
  t_itemindex.value = i
  if (monthenddata.value[i].planDetailData.length === 0) {
    console.log('暂无')
    mounthendshow.value = 0
  } else {
    mounthendshow.value = 1
    // console.log(monthenddata.value[i].planDetailData);
    const arr: any = []
    monthenddata.value[i].planDetailData[0].planSummarizing.forEach(
        (ele: any, index: number) => {
          arr.push(ele.insurCompanyPlanName)
        }
    )
    alarms_models.value = [...arr, ...arr, ...arr]

    // 定义一个数组result来存储最终结果
    const result = []
    // 遍历data数组
    for (const item of monthenddata.value[i].planDetailData) {
      const {day, planSummarizing} = item
      const summary = [day]
      // 遍历planSummarizing数组，将每个对象中的四个值依次加入summary数组中
      for (const p of planSummarizing) {
        const {plusInsurMoney, minusInsurMoney, summarizingMoney} = p
        summary.push(plusInsurMoney)
      }
      for (const p of planSummarizing) {
        const {plusInsurMoney, minusInsurMoney, summarizingMoney} = p
        summary.push(minusInsurMoney)
      }
      for (const p of planSummarizing) {
        const {plusInsurMoney, minusInsurMoney, summarizingMoney} = p
        summary.push(summarizingMoney)
      }
      // 将每个日期对应的数据放入result数组中
      result.push(summary)
    }
    result.forEach((ele: any, index: number) => {
      var num = (ele.length - 1) / 3
      var total = 0
      for (let index = num * 2 + 1; index < num * 2 + 1 + num; index++) {
        total += ele[index]
      }
      ele[ele.length] = total.toFixed(3)
    })
    console.log(result)
    alarms_ir.value = result
  }
}
</script>

<style lang="scss" scoped>
thead {
  position: sticky;
  top: 0px;
  z-index: 4;
}

table tr td:first-child {
  position: sticky;
  left: 0;
  z-index: 999;
  box-shadow: 5px 0 0px #1a191a;
}

table tr td:last-child,
table tr th:last-child {
  position: sticky;
  right: 0;
  z-index: 999;
  box-shadow: -5px 0px 0px #1a191a;
}

.list-table {
  border: 1px solid #f4f4f7;
  font-size: 14px;
  width: 100%;
  margin: 10px 0;
  border-collapse: collapse;

  .aaa {
    background-color: #f4f4f7;
  }

  .bbb {
    background-color: #eaeaef;
  }

  .table-title {
    border: none;
    color: #000000;
    font-weight: 700;

    .tac {
      // position: relative;
      padding: 9px 15px;
      height: 20px;
      line-height: 20px;
      font-weight: normal;
      z-index: 10;
    }
  }

  .table-content {
    border-bottom: 1px solid #f4f4f7;

    .tac1 {
      text-align: center;
      padding: 16px 24px;
      height: 20px;
      min-width: 100px;
      line-height: 20px;
      font-size: 14px;
      background-color: #ffffff;
      color: black;
    }
  }
}

.b {
  margin-top: 20px;
  width: 100%;
  overflow: auto;
}

.t {
  padding-right: 20px;
  display: flex;
  align-items: center;
  // justify-content: space-around;
  flex-wrap: nowrap;
  overflow: auto;

  .t_item {
    box-sizing: border-box;
    margin: 10px;
    flex-shrink: 0;
    width: 330px;
    height: 250px;
    padding: 20px;
    border: 1px solid #f4f4f7;
    border-radius: 10px;
    display: flex;
    justify-content: space-around;

    .t_l {
      div {
        margin-bottom: 10px;

        .small {
          font-size: 19px;
          color: rgba(250, 250, 252, 1);
        }

        .bord {
          font-weight: 700;
        }
      }

      .t_lone {
        display: flex;
        align-items: center;

        span {
          font-weight: 700;
        }

        img {
          margin-right: 15px;
          width: 50px;
          height: 50px;
        }
      }
    }

    .t_r {
      margin-top: 10px;
      cursor: pointer;
      height: 40px;
      box-sizing: border-box;
      padding: 10px;
      background-color: rgba(62, 95, 245, 1);
      display: flex;
      align-items: center;
      border-radius: 10px;
      justify-content: center;
      color: #ffffff;

      img {
        margin-right: 10px;
        width: 14px;
        height: 14px;
      }
    }
  }
}

.table-list {
  margin-top: 20px;

  .tables {
    width: 100%;
    height: 100%;
    display: flex;
    box-sizing: border-box;
    padding: 10px;

    .l {
      width: 20%;
      display: flex;
      flex-direction: column;
      align-items: start;
      padding: 20px;
      box-sizing: border-box;

      .small {
        color: #666;
      }

      .bord {
        font-weight: 700;
      }

      div {
        margin-bottom: 20px;
      }

      .dc_btn {
        cursor: pointer;
        box-sizing: border-box;
        padding: 10px;
        background-color: rgba(62, 95, 245, 1);
        display: flex;
        align-items: center;
        border-radius: 10px;
        justify-content: center;
        color: #ffffff;

        img {
          margin-right: 10px;
          width: 14px;
          height: 14px;
        }
      }

      .top {
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: 700;

        img {
          margin-right: 20px;
          width: 50px;
          height: 50px;
        }
      }
    }

    .r {
      width: 80%;

      // overflow-x: scroll;
      // background-color: pink;
      .r_table {
        border: 1px solid rgba(244, 244, 247, 1);
        height: 100%;
        display: flex;
        flex-direction: column;

        .plan {
          background: #f4f4f7;
          font-weight: 500;
        }

        .tableitem {
          width: 100%;
          flex: 1;
          display: flex;
          align-items: center;

          .title {
            min-width: 100px;
            text-align: center;
            font-weight: 700;
          }
        }
      }
    }
  }
}

.date {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px 0 20px;
}

.tab {
  background-color: white;

  .el-tabs {
    padding-left: 16px;
  }

  .el-tab-pane {
    padding: 16px;
    background-color: #f4f4f7;
    height: 745px;
    overflow: auto;
  }
}

.active {
  border-color: rgba(158, 175, 250, 1) !important;
}

.flc {
  flex: 1;
  text-align: center;
}

.outflc {
  display: flex;
  flex: 1;

  &:not(:last-child) {
    border-right: 1px solid #ccc;
  }
}

// .outflc :last-child{
//   border: none !important;
// }
.left_btn {
  width: 32px;
  height: 22px;

  img {
    width: 100%;
    height: 100%;
  }
}

.left_btn {
  width: 32px;
  height: 22px;

  img {
    width: 100%;
    height: 100%;
  }
}

.bordernone {
  border-right: none !important;
}
</style>
